<html lang="en-US">

<head>
    
<title>「连载十二」优化配置结构及实现图片上传 - 花落雨忧</title>

<meta property="og:title" content="「连载十二」优化配置结构及实现图片上传 - 花落雨忧">



    



    
    <meta property="description" content="这个应用程序跑了那么久了，越来越大，越来越壮，仿佛我们的产品一样，现在它需要进行小范围重构了，以便于后续的使用，这非常重要。
[&amp;hellip;] 一天，产品经理突然跟你说文章列表，没有封面图，不够美观，！）&amp;amp;￥*！&amp;amp;）#&amp;amp;￥*！加一个吧，几分钟的事
你打开你的程序，分析了一波写了个清单：
[&amp;hellip;] 嗯，你发现要较优的话，需要调整部分的应用程序结构，因为功能越来 &amp;hellip;">
    <meta property="og:description" content="这个应用程序跑了那么久了，越来越大，越来越壮，仿佛我们的产品一样，现在它需要进行小范围重构了，以便于后续的使用，这非常重要。
[&amp;hellip;] 一天，产品经理突然跟你说文章列表，没有封面图，不够美观，！）&amp;amp;￥*！&amp;amp;）#&amp;amp;￥*！加一个吧，几分钟的事
你打开你的程序，分析了一波写了个清单：
[&amp;hellip;] 嗯，你发现要较优的话，需要调整部分的应用程序结构，因为功能越来 &amp;hellip;">
    






<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1">

<link rel="shortcut icon" href="https://www.lican.site/logo/logo.png" type="image/x-icon" />



<link rel="stylesheet" href="/css/style.min.css" />

<link rel="stylesheet" href="/css/reset.min.css" />




<script src="https://www.lican.site/js/highlight.min.js"></script>

<script>
hljs.configure({ ignoreUnescapedHTML: true })
hljs.highlightAll();
</script>


<script src="https://www.lican.site/js/jquery.min.js"></script>




<link href="https://www.lican.site/css/hugo-code.min.css" rel="stylesheet" />



    <style>
        .post-content img {
            max-width: 400px;
        }
    </style>
</head>

<body id="period" class="home blog">
    <a class="skip-content" href="#main">Press "Enter" to skip to content</a>
    <div id="overflow-container" class="overflow-container">
        <header class="site-header" id="site-header" role="banner">
    <div class="max-width">
        <div id="title-container" class="title-container">
            <div id="site-title" class="site-title"><a href="/">花落雨忧</a></div>
            <p class="tagline">思所及 力所行 方为真.</p>
        </div>
        
        <div id="menu-primary-container" class="menu-primary-container">
            <div class="icon-container">
            </div>
            <div id="menu-primary" class="menu-container menu-primary" role="navigation">
                <nav class="menu">
                    <ul id="menu-primary-items" class="menu-primary-items">
                        
                        
                        <li id="menu-item-0"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/posts" aria-current="page" tabindex="0">首页</a></li>
                        
                        <li id="menu-item-1"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/tech/" aria-current="page" tabindex="1">技术文档</a></li>
                        
                        <li id="menu-item-2"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/article/" aria-current="page" tabindex="2">文章</a></li>
                        
                        <li id="menu-item-3"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/project/" aria-current="page" tabindex="3">项目</a></li>
                        
                        <li id="menu-item-4"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/about/" aria-current="page" tabindex="4">关于</a></li>
                        
                    </ul>
                </nav>
            </div>
        </div>
    </div>
</header>
        <div id="primary-container" class="primary-container">
            <div class="max-width">
                <section id="main" class="main" role="main">
                    <div id="loop-container" class="loop-container">
                        <div
                            class="post type-post status-publish format-standard hentry entry">
                            <article>
                                <div class="post-container">
                                    <div class="post-header">
                                        <h2 class="post-title">
                                            <a href="/posts/go/gin/2018-05-27-config-upload/">「连载十二」优化配置结构及实现图片上传</a>
                                        </h2>
                                        
                                        <div class="post-byline">Published on
                                            <a class="date" href="javascript:;">2018/05/27</a>
                                            
                                            
                                            
                                            By 
                                            <a class="author" href="javascript:;">煎鱼</a></div>
                                            
                                        
                                    </div>
                                    <div class="post-content">
                                        <h2 id="知识点">知识点</h2>
<ul>
<li>重构、调整结构</li>
</ul>
<h2 id="本文目标">本文目标</h2>
<p>这个应用程序跑了那么久了，越来越大，越来越壮，仿佛我们的产品一样，现在它需要进行小范围重构了，以便于后续的使用，这非常重要。</p>
<h2 id="前言">前言</h2>
<p>一天，产品经理突然跟你说文章列表，没有封面图，不够美观，！）&amp;￥*！&amp;）#&amp;￥*！加一个吧，几分钟的事</p>
<p>你打开你的程序，分析了一波写了个清单：</p>
<ul>
<li>优化配置结构（因为配置项越来越多）</li>
<li>抽离 原 logging 的 File 便于公用（logging、upload 各保有一份并不合适）</li>
<li>实现上传图片接口（需限制文件格式、大小）</li>
<li>修改文章接口（需支持封面地址参数）</li>
<li>增加 blog_article （文章）的数据库字段</li>
<li>实现 http.FileServer</li>
</ul>
<p>嗯，你发现要较优的话，需要调整部分的应用程序结构，因为功能越来越多，原本的设计也要跟上节奏</p>
<p>也就是在适当的时候，及时优化</p>
<h2 id="优化配置结构">优化配置结构</h2>
<h3 id="一讲解">一、讲解</h3>
<p>在先前章节中，采用了直接读取 KEY 的方式去存储配置项，而本次需求中，需要增加图片的配置项，总体就有些冗余了</p>
<p>我们采用以下解决方法：</p>
<ul>
<li>映射结构体：使用 MapTo 来设置配置参数</li>
<li>配置统管：所有的配置项统管到 setting 中</li>
</ul>
<h4 id="映射结构体示例">映射结构体（示例）</h4>
<p>在 go-ini 中可以采用 MapTo 的方式来映射结构体，例如：</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-go" data-lang="go"><span style="color:#66d9ef">type</span> <span style="color:#a6e22e">Server</span> <span style="color:#66d9ef">struct</span> {
	<span style="color:#a6e22e">RunMode</span> <span style="color:#66d9ef">string</span>
	<span style="color:#a6e22e">HttpPort</span> <span style="color:#66d9ef">int</span>
	<span style="color:#a6e22e">ReadTimeout</span> <span style="color:#a6e22e">time</span>.<span style="color:#a6e22e">Duration</span>
	<span style="color:#a6e22e">WriteTimeout</span> <span style="color:#a6e22e">time</span>.<span style="color:#a6e22e">Duration</span>
}

<span style="color:#66d9ef">var</span> <span style="color:#a6e22e">ServerSetting</span> = <span style="color:#f92672">&amp;</span><span style="color:#a6e22e">Server</span>{}

<span style="color:#66d9ef">func</span> <span style="color:#a6e22e">main</span>() {
    <span style="color:#a6e22e">Cfg</span>, <span style="color:#a6e22e">err</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">ini</span>.<span style="color:#a6e22e">Load</span>(<span style="color:#e6db74">&#34;conf/app.ini&#34;</span>)
	<span style="color:#66d9ef">if</span> <span style="color:#a6e22e">err</span> <span style="color:#f92672">!=</span> <span style="color:#66d9ef">nil</span> {
		<span style="color:#a6e22e">log</span>.<span style="color:#a6e22e">Fatalf</span>(<span style="color:#e6db74">&#34;Fail to parse &#39;conf/app.ini&#39;: %v&#34;</span>, <span style="color:#a6e22e">err</span>)
	}

	<span style="color:#a6e22e">err</span> = <span style="color:#a6e22e">Cfg</span>.<span style="color:#a6e22e">Section</span>(<span style="color:#e6db74">&#34;server&#34;</span>).<span style="color:#a6e22e">MapTo</span>(<span style="color:#a6e22e">ServerSetting</span>)
	<span style="color:#66d9ef">if</span> <span style="color:#a6e22e">err</span> <span style="color:#f92672">!=</span> <span style="color:#66d9ef">nil</span> {
		<span style="color:#a6e22e">log</span>.<span style="color:#a6e22e">Fatalf</span>(<span style="color:#e6db74">&#34;Cfg.MapTo ServerSetting err: %v&#34;</span>, <span style="color:#a6e22e">err</span>)
	}
}
</code></pre></div><p>在这段代码中，可以注意 ServerSetting 取了地址，为什么 MapTo 必须地址入参呢？</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-go" data-lang="go"><span style="color:#75715e">// MapTo maps section to given struct.
</span><span style="color:#75715e"></span><span style="color:#66d9ef">func</span> (<span style="color:#a6e22e">s</span> <span style="color:#f92672">*</span><span style="color:#a6e22e">Section</span>) <span style="color:#a6e22e">MapTo</span>(<span style="color:#a6e22e">v</span> <span style="color:#66d9ef">interface</span>{}) <span style="color:#66d9ef">error</span> {
	<span style="color:#a6e22e">typ</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">reflect</span>.<span style="color:#a6e22e">TypeOf</span>(<span style="color:#a6e22e">v</span>)
	<span style="color:#a6e22e">val</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">reflect</span>.<span style="color:#a6e22e">ValueOf</span>(<span style="color:#a6e22e">v</span>)
	<span style="color:#66d9ef">if</span> <span style="color:#a6e22e">typ</span>.<span style="color:#a6e22e">Kind</span>() <span style="color:#f92672">==</span> <span style="color:#a6e22e">reflect</span>.<span style="color:#a6e22e">Ptr</span> {
		<span style="color:#a6e22e">typ</span> = <span style="color:#a6e22e">typ</span>.<span style="color:#a6e22e">Elem</span>()
		<span style="color:#a6e22e">val</span> = <span style="color:#a6e22e">val</span>.<span style="color:#a6e22e">Elem</span>()
	} <span style="color:#66d9ef">else</span> {
		<span style="color:#66d9ef">return</span> <span style="color:#a6e22e">errors</span>.<span style="color:#a6e22e">New</span>(<span style="color:#e6db74">&#34;cannot map to non-pointer struct&#34;</span>)
	}

	<span style="color:#66d9ef">return</span> <span style="color:#a6e22e">s</span>.<span style="color:#a6e22e">mapTo</span>(<span style="color:#a6e22e">val</span>, <span style="color:#66d9ef">false</span>)
}
</code></pre></div><p>在 MapTo 中 <code>typ.Kind() == reflect.Ptr</code> 约束了必须使用指针，否则会返回 <code>cannot map to non-pointer struct</code> 的错误。这个是表面原因</p>
<p>更往内探究，可以认为是 <code>field.Set</code> 的原因，当执行 <code>val := reflect.ValueOf(v)</code> ，函数通过传递 <code>v</code> 拷贝创建了 <code>val</code>，但是 <code>val</code> 的改变并不能更改原始的 <code>v</code>，要想 <code>val</code> 的更改能作用到 <code>v</code>，则必须传递 <code>v</code> 的地址</p>
<p>显然 go-ini 里也是包含修改原始值这一项功能的，你觉得是什么原因呢？</p>
<h4 id="配置统管">配置统管</h4>
<p>在先前的版本中，models 和 file 的配置是在自己的文件中解析的，而其他在 setting.go 中，因此我们需要将其在 setting 中统一接管</p>
<p>你可能会想，直接把两者的配置项复制粘贴到 setting.go 的 init 中，一下子就完事了，搞那么麻烦？</p>
<p>但你在想想，先前的代码中存在多个 init 函数，执行顺序存在问题，无法达到我们的要求，你可以试试</p>
<p>（此处是一个基础知识点）</p>
<p>在 Go 中，当存在多个 init 函数时，执行顺序为：</p>
<ul>
<li>相同包下的 init 函数：按照源文件编译顺序决定执行顺序（默认按文件名排序）</li>
<li>不同包下的 init 函数：按照包导入的依赖关系决定先后顺序</li>
</ul>
<p>所以要避免多 init 的情况，<strong>尽量由程序把控初始化的先后顺序</strong></p>
<h3 id="二落实">二、落实</h3>
<h4 id="修改配置文件">修改配置文件</h4>
<p>打开 conf/app.ini 将配置文件修改为大驼峰命名，另外我们增加了 5 个配置项用于上传图片的功能，4 个文件日志方面的配置项</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-ini" data-lang="ini"><span style="color:#66d9ef">[app]</span>
<span style="color:#a6e22e">PageSize</span> <span style="color:#f92672">=</span> <span style="color:#e6db74">10</span>
<span style="color:#a6e22e">JwtSecret</span> <span style="color:#f92672">=</span> <span style="color:#e6db74">233</span>

<span style="color:#a6e22e">RuntimeRootPath</span> <span style="color:#f92672">=</span> <span style="color:#e6db74">runtime/</span>

<span style="color:#a6e22e">ImagePrefixUrl</span> <span style="color:#f92672">=</span> <span style="color:#e6db74">http://127.0.0.1:8000</span>
<span style="color:#a6e22e">ImageSavePath</span> <span style="color:#f92672">=</span> <span style="color:#e6db74">upload/images/</span>
<span style="color:#75715e"># MB</span>
<span style="color:#a6e22e">ImageMaxSize</span> <span style="color:#f92672">=</span> <span style="color:#e6db74">5</span>
<span style="color:#a6e22e">ImageAllowExts</span> <span style="color:#f92672">=</span> <span style="color:#e6db74">.jpg,.jpeg,.png</span>

<span style="color:#a6e22e">LogSavePath</span> <span style="color:#f92672">=</span> <span style="color:#e6db74">logs/</span>
<span style="color:#a6e22e">LogSaveName</span> <span style="color:#f92672">=</span> <span style="color:#e6db74">log</span>
<span style="color:#a6e22e">LogFileExt</span> <span style="color:#f92672">=</span> <span style="color:#e6db74">log</span>
<span style="color:#a6e22e">TimeFormat</span> <span style="color:#f92672">=</span> <span style="color:#e6db74">20060102</span>

<span style="color:#66d9ef">[server]</span>
<span style="color:#75715e">#debug or release</span>
<span style="color:#a6e22e">RunMode</span> <span style="color:#f92672">=</span> <span style="color:#e6db74">debug</span>
<span style="color:#a6e22e">HttpPort</span> <span style="color:#f92672">=</span> <span style="color:#e6db74">8000</span>
<span style="color:#a6e22e">ReadTimeout</span> <span style="color:#f92672">=</span> <span style="color:#e6db74">60</span>
<span style="color:#a6e22e">WriteTimeout</span> <span style="color:#f92672">=</span> <span style="color:#e6db74">60</span>

<span style="color:#66d9ef">[database]</span>
<span style="color:#a6e22e">Type</span> <span style="color:#f92672">=</span> <span style="color:#e6db74">mysql</span>
<span style="color:#a6e22e">User</span> <span style="color:#f92672">=</span> <span style="color:#e6db74">root</span>
<span style="color:#a6e22e">Password</span> <span style="color:#f92672">=</span> <span style="color:#e6db74">rootroot</span>
<span style="color:#a6e22e">Host</span> <span style="color:#f92672">=</span> <span style="color:#e6db74">127.0.0.1:3306</span>
<span style="color:#a6e22e">Name</span> <span style="color:#f92672">=</span> <span style="color:#e6db74">blog</span>
<span style="color:#a6e22e">TablePrefix</span> <span style="color:#f92672">=</span> <span style="color:#e6db74">blog_</span>
</code></pre></div><h4 id="优化配置读取及设置初始化顺序">优化配置读取及设置初始化顺序</h4>
<h5 id="第一步">第一步</h5>
<p>将散落在其他文件里的配置都删掉，<strong>统一在 setting 中处理</strong>以及<strong>修改 init 函数为 Setup 方法</strong></p>
<p>打开 pkg/setting/setting.go 文件，修改如下：</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-go" data-lang="go"><span style="color:#f92672">package</span> <span style="color:#a6e22e">setting</span>

<span style="color:#f92672">import</span> (
	<span style="color:#e6db74">&#34;log&#34;</span>
	<span style="color:#e6db74">&#34;time&#34;</span>

	<span style="color:#e6db74">&#34;github.com/go-ini/ini&#34;</span>
)

<span style="color:#66d9ef">type</span> <span style="color:#a6e22e">App</span> <span style="color:#66d9ef">struct</span> {
	<span style="color:#a6e22e">JwtSecret</span> <span style="color:#66d9ef">string</span>
	<span style="color:#a6e22e">PageSize</span> <span style="color:#66d9ef">int</span>
	<span style="color:#a6e22e">RuntimeRootPath</span> <span style="color:#66d9ef">string</span>

	<span style="color:#a6e22e">ImagePrefixUrl</span> <span style="color:#66d9ef">string</span>
	<span style="color:#a6e22e">ImageSavePath</span> <span style="color:#66d9ef">string</span>
	<span style="color:#a6e22e">ImageMaxSize</span> <span style="color:#66d9ef">int</span>
	<span style="color:#a6e22e">ImageAllowExts</span> []<span style="color:#66d9ef">string</span>

	<span style="color:#a6e22e">LogSavePath</span> <span style="color:#66d9ef">string</span>
	<span style="color:#a6e22e">LogSaveName</span> <span style="color:#66d9ef">string</span>
	<span style="color:#a6e22e">LogFileExt</span> <span style="color:#66d9ef">string</span>
	<span style="color:#a6e22e">TimeFormat</span> <span style="color:#66d9ef">string</span>
}

<span style="color:#66d9ef">var</span> <span style="color:#a6e22e">AppSetting</span> = <span style="color:#f92672">&amp;</span><span style="color:#a6e22e">App</span>{}

<span style="color:#66d9ef">type</span> <span style="color:#a6e22e">Server</span> <span style="color:#66d9ef">struct</span> {
	<span style="color:#a6e22e">RunMode</span> <span style="color:#66d9ef">string</span>
	<span style="color:#a6e22e">HttpPort</span> <span style="color:#66d9ef">int</span>
	<span style="color:#a6e22e">ReadTimeout</span> <span style="color:#a6e22e">time</span>.<span style="color:#a6e22e">Duration</span>
	<span style="color:#a6e22e">WriteTimeout</span> <span style="color:#a6e22e">time</span>.<span style="color:#a6e22e">Duration</span>
}

<span style="color:#66d9ef">var</span> <span style="color:#a6e22e">ServerSetting</span> = <span style="color:#f92672">&amp;</span><span style="color:#a6e22e">Server</span>{}

<span style="color:#66d9ef">type</span> <span style="color:#a6e22e">Database</span> <span style="color:#66d9ef">struct</span> {
	<span style="color:#a6e22e">Type</span> <span style="color:#66d9ef">string</span>
	<span style="color:#a6e22e">User</span> <span style="color:#66d9ef">string</span>
	<span style="color:#a6e22e">Password</span> <span style="color:#66d9ef">string</span>
	<span style="color:#a6e22e">Host</span> <span style="color:#66d9ef">string</span>
	<span style="color:#a6e22e">Name</span> <span style="color:#66d9ef">string</span>
	<span style="color:#a6e22e">TablePrefix</span> <span style="color:#66d9ef">string</span>
}

<span style="color:#66d9ef">var</span> <span style="color:#a6e22e">DatabaseSetting</span> = <span style="color:#f92672">&amp;</span><span style="color:#a6e22e">Database</span>{}

<span style="color:#66d9ef">func</span> <span style="color:#a6e22e">Setup</span>() {
	<span style="color:#a6e22e">Cfg</span>, <span style="color:#a6e22e">err</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">ini</span>.<span style="color:#a6e22e">Load</span>(<span style="color:#e6db74">&#34;conf/app.ini&#34;</span>)
	<span style="color:#66d9ef">if</span> <span style="color:#a6e22e">err</span> <span style="color:#f92672">!=</span> <span style="color:#66d9ef">nil</span> {
		<span style="color:#a6e22e">log</span>.<span style="color:#a6e22e">Fatalf</span>(<span style="color:#e6db74">&#34;Fail to parse &#39;conf/app.ini&#39;: %v&#34;</span>, <span style="color:#a6e22e">err</span>)
	}

	<span style="color:#a6e22e">err</span> = <span style="color:#a6e22e">Cfg</span>.<span style="color:#a6e22e">Section</span>(<span style="color:#e6db74">&#34;app&#34;</span>).<span style="color:#a6e22e">MapTo</span>(<span style="color:#a6e22e">AppSetting</span>)
	<span style="color:#66d9ef">if</span> <span style="color:#a6e22e">err</span> <span style="color:#f92672">!=</span> <span style="color:#66d9ef">nil</span> {
		<span style="color:#a6e22e">log</span>.<span style="color:#a6e22e">Fatalf</span>(<span style="color:#e6db74">&#34;Cfg.MapTo AppSetting err: %v&#34;</span>, <span style="color:#a6e22e">err</span>)
	}

	<span style="color:#a6e22e">AppSetting</span>.<span style="color:#a6e22e">ImageMaxSize</span> = <span style="color:#a6e22e">AppSetting</span>.<span style="color:#a6e22e">ImageMaxSize</span> <span style="color:#f92672">*</span> <span style="color:#ae81ff">1024</span> <span style="color:#f92672">*</span> <span style="color:#ae81ff">1024</span>

	<span style="color:#a6e22e">err</span> = <span style="color:#a6e22e">Cfg</span>.<span style="color:#a6e22e">Section</span>(<span style="color:#e6db74">&#34;server&#34;</span>).<span style="color:#a6e22e">MapTo</span>(<span style="color:#a6e22e">ServerSetting</span>)
	<span style="color:#66d9ef">if</span> <span style="color:#a6e22e">err</span> <span style="color:#f92672">!=</span> <span style="color:#66d9ef">nil</span> {
		<span style="color:#a6e22e">log</span>.<span style="color:#a6e22e">Fatalf</span>(<span style="color:#e6db74">&#34;Cfg.MapTo ServerSetting err: %v&#34;</span>, <span style="color:#a6e22e">err</span>)
	}

	<span style="color:#a6e22e">ServerSetting</span>.<span style="color:#a6e22e">ReadTimeout</span> = <span style="color:#a6e22e">ServerSetting</span>.<span style="color:#a6e22e">ReadTimeout</span> <span style="color:#f92672">*</span> <span style="color:#a6e22e">time</span>.<span style="color:#a6e22e">Second</span>
	<span style="color:#a6e22e">ServerSetting</span>.<span style="color:#a6e22e">WriteTimeout</span> = <span style="color:#a6e22e">ServerSetting</span>.<span style="color:#a6e22e">WriteTimeout</span> <span style="color:#f92672">*</span> <span style="color:#a6e22e">time</span>.<span style="color:#a6e22e">Second</span>

	<span style="color:#a6e22e">err</span> = <span style="color:#a6e22e">Cfg</span>.<span style="color:#a6e22e">Section</span>(<span style="color:#e6db74">&#34;database&#34;</span>).<span style="color:#a6e22e">MapTo</span>(<span style="color:#a6e22e">DatabaseSetting</span>)
	<span style="color:#66d9ef">if</span> <span style="color:#a6e22e">err</span> <span style="color:#f92672">!=</span> <span style="color:#66d9ef">nil</span> {
		<span style="color:#a6e22e">log</span>.<span style="color:#a6e22e">Fatalf</span>(<span style="color:#e6db74">&#34;Cfg.MapTo DatabaseSetting err: %v&#34;</span>, <span style="color:#a6e22e">err</span>)
	}
}
</code></pre></div><p>在这里，我们做了如下几件事：</p>
<ul>
<li>编写与配置项保持一致的结构体（App、Server、Database）</li>
<li>使用 MapTo 将配置项映射到结构体上</li>
<li>对一些需特殊设置的配置项进行再赋值</li>
</ul>
<p><strong>需要你去做的事：</strong></p>
<ul>
<li>将 <a href="https://github.com/EDDYCJY/go-gin-example/blob/a338ddec103c9506b4c7ed16d9f5386040d99b4b/models/models.go#L23">models.go</a>、<a href="https://github.com/EDDYCJY/go-gin-example/blob/a338ddec103c9506b4c7ed16d9f5386040d99b4b/pkg/setting/setting.go#L23">setting.go</a>、<a href="https://github.com/EDDYCJY/go-gin-example/blob/a338ddec103c9506b4c7ed16d9f5386040d99b4b/pkg/logging/log.go#L32-L37">pkg/logging/log.go</a> 的 init 函数修改为 Setup 方法</li>
<li>将 <a href="https://github.com/EDDYCJY/go-gin-example/blob/a338ddec103c9506b4c7ed16d9f5386040d99b4b/models/models.go#L23-L39">models/models.go</a> 独立读取的 DB 配置项删除，改为统一读取 setting</li>
<li>将 <a href="https://github.com/EDDYCJY/go-gin-example/blob/a338ddec103c9506b4c7ed16d9f5386040d99b4b/pkg/logging/file.go#L10-L15">pkg/logging/file</a> 独立的 LOG 配置项删除，改为统一读取 setting</li>
</ul>
<p>这几项比较基础，并没有贴出来，我希望你可以自己动手，有问题的话可右拐 <a href="https://github.com/EDDYCJY/go-gin-example">项目地址</a></p>
<h5 id="第二步">第二步</h5>
<p>在这一步我们要设置初始化的流程，打开 main.go 文件，修改内容：</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-go" data-lang="go"><span style="color:#66d9ef">func</span> <span style="color:#a6e22e">main</span>() {
	<span style="color:#a6e22e">setting</span>.<span style="color:#a6e22e">Setup</span>()
	<span style="color:#a6e22e">models</span>.<span style="color:#a6e22e">Setup</span>()
	<span style="color:#a6e22e">logging</span>.<span style="color:#a6e22e">Setup</span>()

	<span style="color:#a6e22e">endless</span>.<span style="color:#a6e22e">DefaultReadTimeOut</span> = <span style="color:#a6e22e">setting</span>.<span style="color:#a6e22e">ServerSetting</span>.<span style="color:#a6e22e">ReadTimeout</span>
	<span style="color:#a6e22e">endless</span>.<span style="color:#a6e22e">DefaultWriteTimeOut</span> = <span style="color:#a6e22e">setting</span>.<span style="color:#a6e22e">ServerSetting</span>.<span style="color:#a6e22e">WriteTimeout</span>
	<span style="color:#a6e22e">endless</span>.<span style="color:#a6e22e">DefaultMaxHeaderBytes</span> = <span style="color:#ae81ff">1</span> <span style="color:#f92672">&lt;&lt;</span> <span style="color:#ae81ff">20</span>
	<span style="color:#a6e22e">endPoint</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">fmt</span>.<span style="color:#a6e22e">Sprintf</span>(<span style="color:#e6db74">&#34;:%d&#34;</span>, <span style="color:#a6e22e">setting</span>.<span style="color:#a6e22e">ServerSetting</span>.<span style="color:#a6e22e">HttpPort</span>)

	<span style="color:#a6e22e">server</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">endless</span>.<span style="color:#a6e22e">NewServer</span>(<span style="color:#a6e22e">endPoint</span>, <span style="color:#a6e22e">routers</span>.<span style="color:#a6e22e">InitRouter</span>())
	<span style="color:#a6e22e">server</span>.<span style="color:#a6e22e">BeforeBegin</span> = <span style="color:#66d9ef">func</span>(<span style="color:#a6e22e">add</span> <span style="color:#66d9ef">string</span>) {
		<span style="color:#a6e22e">log</span>.<span style="color:#a6e22e">Printf</span>(<span style="color:#e6db74">&#34;Actual pid is %d&#34;</span>, <span style="color:#a6e22e">syscall</span>.<span style="color:#a6e22e">Getpid</span>())
	}

	<span style="color:#a6e22e">err</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">server</span>.<span style="color:#a6e22e">ListenAndServe</span>()
	<span style="color:#66d9ef">if</span> <span style="color:#a6e22e">err</span> <span style="color:#f92672">!=</span> <span style="color:#66d9ef">nil</span> {
		<span style="color:#a6e22e">log</span>.<span style="color:#a6e22e">Printf</span>(<span style="color:#e6db74">&#34;Server err: %v&#34;</span>, <span style="color:#a6e22e">err</span>)
	}
}
</code></pre></div><p>修改完毕后，就成功将多模块的初始化函数放到启动流程中了（先后顺序也可以控制）</p>
<h5 id="验证">验证</h5>
<p>在这里为止，针对本需求的配置优化就完毕了，你需要执行 <code>go run main.go</code> 验证一下你的功能是否正常哦</p>
<p>顺带留个基础问题，大家可以思考下</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-go" data-lang="go"><span style="color:#a6e22e">ServerSetting</span>.<span style="color:#a6e22e">ReadTimeout</span> = <span style="color:#a6e22e">ServerSetting</span>.<span style="color:#a6e22e">ReadTimeout</span> <span style="color:#f92672">*</span> <span style="color:#a6e22e">time</span>.<span style="color:#a6e22e">Second</span>
<span style="color:#a6e22e">ServerSetting</span>.<span style="color:#a6e22e">WriteTimeout</span> = <span style="color:#a6e22e">ServerSetting</span>.<span style="color:#a6e22e">ReadTimeout</span> <span style="color:#f92672">*</span> <span style="color:#a6e22e">time</span>.<span style="color:#a6e22e">Second</span>
</code></pre></div><p>若将 setting.go 文件中的这两行删除，会出现什么问题，为什么呢？</p>
<h2 id="抽离-file">抽离 File</h2>
<p>在先前版本中，在 <a href="https://github.com/EDDYCJY/go-gin-example/blob/a338ddec103c9506b4c7ed16d9f5386040d99b4b/pkg/logging/file.go">logging/file.go</a> 中使用到了 os 的一些方法，我们通过前期规划发现，这部分在上传图片功能中可以复用</p>
<h3 id="第一步-1">第一步</h3>
<p>在 pkg 目录下新建 file/file.go ，写入文件内容如下：</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-go" data-lang="go"><span style="color:#f92672">package</span> <span style="color:#a6e22e">file</span>

<span style="color:#f92672">import</span> (
	<span style="color:#e6db74">&#34;os&#34;</span>
	<span style="color:#e6db74">&#34;path&#34;</span>
	<span style="color:#e6db74">&#34;mime/multipart&#34;</span>
	<span style="color:#e6db74">&#34;io/ioutil&#34;</span>
)

<span style="color:#66d9ef">func</span> <span style="color:#a6e22e">GetSize</span>(<span style="color:#a6e22e">f</span> <span style="color:#a6e22e">multipart</span>.<span style="color:#a6e22e">File</span>) (<span style="color:#66d9ef">int</span>, <span style="color:#66d9ef">error</span>) {
	<span style="color:#a6e22e">content</span>, <span style="color:#a6e22e">err</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">ioutil</span>.<span style="color:#a6e22e">ReadAll</span>(<span style="color:#a6e22e">f</span>)

	<span style="color:#66d9ef">return</span> len(<span style="color:#a6e22e">content</span>), <span style="color:#a6e22e">err</span>
}

<span style="color:#66d9ef">func</span> <span style="color:#a6e22e">GetExt</span>(<span style="color:#a6e22e">fileName</span> <span style="color:#66d9ef">string</span>) <span style="color:#66d9ef">string</span> {
	<span style="color:#66d9ef">return</span> <span style="color:#a6e22e">path</span>.<span style="color:#a6e22e">Ext</span>(<span style="color:#a6e22e">fileName</span>)
}

<span style="color:#66d9ef">func</span> <span style="color:#a6e22e">CheckNotExist</span>(<span style="color:#a6e22e">src</span> <span style="color:#66d9ef">string</span>) <span style="color:#66d9ef">bool</span> {
	<span style="color:#a6e22e">_</span>, <span style="color:#a6e22e">err</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">os</span>.<span style="color:#a6e22e">Stat</span>(<span style="color:#a6e22e">src</span>)

	<span style="color:#66d9ef">return</span> <span style="color:#a6e22e">os</span>.<span style="color:#a6e22e">IsNotExist</span>(<span style="color:#a6e22e">err</span>)
}

<span style="color:#66d9ef">func</span> <span style="color:#a6e22e">CheckPermission</span>(<span style="color:#a6e22e">src</span> <span style="color:#66d9ef">string</span>) <span style="color:#66d9ef">bool</span> {
	<span style="color:#a6e22e">_</span>, <span style="color:#a6e22e">err</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">os</span>.<span style="color:#a6e22e">Stat</span>(<span style="color:#a6e22e">src</span>)

	<span style="color:#66d9ef">return</span> <span style="color:#a6e22e">os</span>.<span style="color:#a6e22e">IsPermission</span>(<span style="color:#a6e22e">err</span>)
}

<span style="color:#66d9ef">func</span> <span style="color:#a6e22e">IsNotExistMkDir</span>(<span style="color:#a6e22e">src</span> <span style="color:#66d9ef">string</span>) <span style="color:#66d9ef">error</span> {
	<span style="color:#66d9ef">if</span> <span style="color:#a6e22e">notExist</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">CheckNotExist</span>(<span style="color:#a6e22e">src</span>); <span style="color:#a6e22e">notExist</span> <span style="color:#f92672">==</span> <span style="color:#66d9ef">true</span> {
		<span style="color:#66d9ef">if</span> <span style="color:#a6e22e">err</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">MkDir</span>(<span style="color:#a6e22e">src</span>); <span style="color:#a6e22e">err</span> <span style="color:#f92672">!=</span> <span style="color:#66d9ef">nil</span> {
			<span style="color:#66d9ef">return</span> <span style="color:#a6e22e">err</span>
		}
	}

	<span style="color:#66d9ef">return</span> <span style="color:#66d9ef">nil</span>
}

<span style="color:#66d9ef">func</span> <span style="color:#a6e22e">MkDir</span>(<span style="color:#a6e22e">src</span> <span style="color:#66d9ef">string</span>) <span style="color:#66d9ef">error</span> {
	<span style="color:#a6e22e">err</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">os</span>.<span style="color:#a6e22e">MkdirAll</span>(<span style="color:#a6e22e">src</span>, <span style="color:#a6e22e">os</span>.<span style="color:#a6e22e">ModePerm</span>)
	<span style="color:#66d9ef">if</span> <span style="color:#a6e22e">err</span> <span style="color:#f92672">!=</span> <span style="color:#66d9ef">nil</span> {
		<span style="color:#66d9ef">return</span> <span style="color:#a6e22e">err</span>
	}

	<span style="color:#66d9ef">return</span> <span style="color:#66d9ef">nil</span>
}

<span style="color:#66d9ef">func</span> <span style="color:#a6e22e">Open</span>(<span style="color:#a6e22e">name</span> <span style="color:#66d9ef">string</span>, <span style="color:#a6e22e">flag</span> <span style="color:#66d9ef">int</span>, <span style="color:#a6e22e">perm</span> <span style="color:#a6e22e">os</span>.<span style="color:#a6e22e">FileMode</span>) (<span style="color:#f92672">*</span><span style="color:#a6e22e">os</span>.<span style="color:#a6e22e">File</span>, <span style="color:#66d9ef">error</span>) {
	<span style="color:#a6e22e">f</span>, <span style="color:#a6e22e">err</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">os</span>.<span style="color:#a6e22e">OpenFile</span>(<span style="color:#a6e22e">name</span>, <span style="color:#a6e22e">flag</span>, <span style="color:#a6e22e">perm</span>)
	<span style="color:#66d9ef">if</span> <span style="color:#a6e22e">err</span> <span style="color:#f92672">!=</span> <span style="color:#66d9ef">nil</span> {
		<span style="color:#66d9ef">return</span> <span style="color:#66d9ef">nil</span>, <span style="color:#a6e22e">err</span>
	}

	<span style="color:#66d9ef">return</span> <span style="color:#a6e22e">f</span>, <span style="color:#66d9ef">nil</span>
}
</code></pre></div><p>在这里我们一共封装了 7 个 方法</p>
<ul>
<li>GetSize：获取文件大小</li>
<li>GetExt：获取文件后缀</li>
<li>CheckNotExist：检查文件是否存在</li>
<li>CheckPermission：检查文件权限</li>
<li>IsNotExistMkDir：如果不存在则新建文件夹</li>
<li>MkDir：新建文件夹</li>
<li>Open：打开文件</li>
</ul>
<p>在这里我们用到了 <code>mime/multipart</code> 包，它主要实现了 MIME 的 multipart 解析，主要适用于 <a href="https://tools.ietf.org/html/rfc2388">HTTP</a> 和常见浏览器生成的 multipart 主体</p>
<p>multipart 又是什么，<a href="https://tools.ietf.org/html/rfc2388">rfc2388</a> 的 multipart/form-data 了解一下</p>
<h3 id="第二步-1">第二步</h3>
<p>我们在第一步已经将 file 重新封装了一层，在这一步我们将原先 logging 包的方法都修改掉</p>
<p>1、打开 pkg/logging/file.go 文件，修改文件内容：</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-go" data-lang="go"><span style="color:#f92672">package</span> <span style="color:#a6e22e">logging</span>

<span style="color:#f92672">import</span> (
	<span style="color:#e6db74">&#34;fmt&#34;</span>
	<span style="color:#e6db74">&#34;os&#34;</span>
	<span style="color:#e6db74">&#34;time&#34;</span>

	<span style="color:#e6db74">&#34;github.com/EDDYCJY/go-gin-example/pkg/setting&#34;</span>
	<span style="color:#e6db74">&#34;github.com/EDDYCJY/go-gin-example/pkg/file&#34;</span>
)

<span style="color:#66d9ef">func</span> <span style="color:#a6e22e">getLogFilePath</span>() <span style="color:#66d9ef">string</span> {
	<span style="color:#66d9ef">return</span> <span style="color:#a6e22e">fmt</span>.<span style="color:#a6e22e">Sprintf</span>(<span style="color:#e6db74">&#34;%s%s&#34;</span>, <span style="color:#a6e22e">setting</span>.<span style="color:#a6e22e">AppSetting</span>.<span style="color:#a6e22e">RuntimeRootPath</span>, <span style="color:#a6e22e">setting</span>.<span style="color:#a6e22e">AppSetting</span>.<span style="color:#a6e22e">LogSavePath</span>)
}

<span style="color:#66d9ef">func</span> <span style="color:#a6e22e">getLogFileName</span>() <span style="color:#66d9ef">string</span> {
	<span style="color:#66d9ef">return</span> <span style="color:#a6e22e">fmt</span>.<span style="color:#a6e22e">Sprintf</span>(<span style="color:#e6db74">&#34;%s%s.%s&#34;</span>,
		<span style="color:#a6e22e">setting</span>.<span style="color:#a6e22e">AppSetting</span>.<span style="color:#a6e22e">LogSaveName</span>,
		<span style="color:#a6e22e">time</span>.<span style="color:#a6e22e">Now</span>().<span style="color:#a6e22e">Format</span>(<span style="color:#a6e22e">setting</span>.<span style="color:#a6e22e">AppSetting</span>.<span style="color:#a6e22e">TimeFormat</span>),
		<span style="color:#a6e22e">setting</span>.<span style="color:#a6e22e">AppSetting</span>.<span style="color:#a6e22e">LogFileExt</span>,
	)
}

<span style="color:#66d9ef">func</span> <span style="color:#a6e22e">openLogFile</span>(<span style="color:#a6e22e">fileName</span>, <span style="color:#a6e22e">filePath</span> <span style="color:#66d9ef">string</span>) (<span style="color:#f92672">*</span><span style="color:#a6e22e">os</span>.<span style="color:#a6e22e">File</span>, <span style="color:#66d9ef">error</span>) {
	<span style="color:#a6e22e">dir</span>, <span style="color:#a6e22e">err</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">os</span>.<span style="color:#a6e22e">Getwd</span>()
	<span style="color:#66d9ef">if</span> <span style="color:#a6e22e">err</span> <span style="color:#f92672">!=</span> <span style="color:#66d9ef">nil</span> {
		<span style="color:#66d9ef">return</span> <span style="color:#66d9ef">nil</span>, <span style="color:#a6e22e">fmt</span>.<span style="color:#a6e22e">Errorf</span>(<span style="color:#e6db74">&#34;os.Getwd err: %v&#34;</span>, <span style="color:#a6e22e">err</span>)
	}

	<span style="color:#a6e22e">src</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">dir</span> <span style="color:#f92672">+</span> <span style="color:#e6db74">&#34;/&#34;</span> <span style="color:#f92672">+</span> <span style="color:#a6e22e">filePath</span>
	<span style="color:#a6e22e">perm</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">file</span>.<span style="color:#a6e22e">CheckPermission</span>(<span style="color:#a6e22e">src</span>)
	<span style="color:#66d9ef">if</span> <span style="color:#a6e22e">perm</span> <span style="color:#f92672">==</span> <span style="color:#66d9ef">true</span> {
		<span style="color:#66d9ef">return</span> <span style="color:#66d9ef">nil</span>, <span style="color:#a6e22e">fmt</span>.<span style="color:#a6e22e">Errorf</span>(<span style="color:#e6db74">&#34;file.CheckPermission Permission denied src: %s&#34;</span>, <span style="color:#a6e22e">src</span>)
	}

	<span style="color:#a6e22e">err</span> = <span style="color:#a6e22e">file</span>.<span style="color:#a6e22e">IsNotExistMkDir</span>(<span style="color:#a6e22e">src</span>)
	<span style="color:#66d9ef">if</span> <span style="color:#a6e22e">err</span> <span style="color:#f92672">!=</span> <span style="color:#66d9ef">nil</span> {
		<span style="color:#66d9ef">return</span> <span style="color:#66d9ef">nil</span>, <span style="color:#a6e22e">fmt</span>.<span style="color:#a6e22e">Errorf</span>(<span style="color:#e6db74">&#34;file.IsNotExistMkDir src: %s, err: %v&#34;</span>, <span style="color:#a6e22e">src</span>, <span style="color:#a6e22e">err</span>)
	}

	<span style="color:#a6e22e">f</span>, <span style="color:#a6e22e">err</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">file</span>.<span style="color:#a6e22e">Open</span>(<span style="color:#a6e22e">src</span> <span style="color:#f92672">+</span> <span style="color:#a6e22e">fileName</span>, <span style="color:#a6e22e">os</span>.<span style="color:#a6e22e">O_APPEND</span>|<span style="color:#a6e22e">os</span>.<span style="color:#a6e22e">O_CREATE</span>|<span style="color:#a6e22e">os</span>.<span style="color:#a6e22e">O_WRONLY</span>, <span style="color:#ae81ff">0644</span>)
	<span style="color:#66d9ef">if</span> <span style="color:#a6e22e">err</span> <span style="color:#f92672">!=</span> <span style="color:#66d9ef">nil</span> {
		<span style="color:#66d9ef">return</span> <span style="color:#66d9ef">nil</span>, <span style="color:#a6e22e">fmt</span>.<span style="color:#a6e22e">Errorf</span>(<span style="color:#e6db74">&#34;Fail to OpenFile :%v&#34;</span>, <span style="color:#a6e22e">err</span>)
	}

	<span style="color:#66d9ef">return</span> <span style="color:#a6e22e">f</span>, <span style="color:#66d9ef">nil</span>
}
</code></pre></div><p>我们将引用都改为了 file/file.go 包里的方法</p>
<p>2、打开 pkg/logging/log.go 文件，修改文件内容:</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-go" data-lang="go"><span style="color:#f92672">package</span> <span style="color:#a6e22e">logging</span>

<span style="color:#f92672">...</span>

<span style="color:#66d9ef">func</span> <span style="color:#a6e22e">Setup</span>() {
	<span style="color:#66d9ef">var</span> <span style="color:#a6e22e">err</span> <span style="color:#66d9ef">error</span>
	<span style="color:#a6e22e">filePath</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">getLogFilePath</span>()
	<span style="color:#a6e22e">fileName</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">getLogFileName</span>()
	<span style="color:#a6e22e">F</span>, <span style="color:#a6e22e">err</span> = <span style="color:#a6e22e">openLogFile</span>(<span style="color:#a6e22e">fileName</span>, <span style="color:#a6e22e">filePath</span>)
	<span style="color:#66d9ef">if</span> <span style="color:#a6e22e">err</span> <span style="color:#f92672">!=</span> <span style="color:#66d9ef">nil</span> {
		<span style="color:#a6e22e">log</span>.<span style="color:#a6e22e">Fatalln</span>(<span style="color:#a6e22e">err</span>)
	}

	<span style="color:#a6e22e">logger</span> = <span style="color:#a6e22e">log</span>.<span style="color:#a6e22e">New</span>(<span style="color:#a6e22e">F</span>, <span style="color:#a6e22e">DefaultPrefix</span>, <span style="color:#a6e22e">log</span>.<span style="color:#a6e22e">LstdFlags</span>)
}

<span style="color:#f92672">...</span>
</code></pre></div><p>由于原方法形参改变了，因此 openLogFile 也需要调整</p>
<h2 id="实现上传图片接口">实现上传图片接口</h2>
<p>这一小节，我们开始实现上次图片相关的一些方法和功能</p>
<p>首先需要在 blog_article 中增加字段 <code>cover_image_url</code>，格式为 <code>varchar(255) DEFAULT '' COMMENT '封面图片地址'</code></p>
<h3 id="第零步">第零步</h3>
<p>一般不会直接将上传的图片名暴露出来，因此我们对图片名进行 MD5 来达到这个效果</p>
<p>在 util 目录下新建 md5.go，写入文件内容：</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-go" data-lang="go"><span style="color:#f92672">package</span> <span style="color:#a6e22e">util</span>

<span style="color:#f92672">import</span> (
	<span style="color:#e6db74">&#34;crypto/md5&#34;</span>
	<span style="color:#e6db74">&#34;encoding/hex&#34;</span>
)

<span style="color:#66d9ef">func</span> <span style="color:#a6e22e">EncodeMD5</span>(<span style="color:#a6e22e">value</span> <span style="color:#66d9ef">string</span>) <span style="color:#66d9ef">string</span> {
	<span style="color:#a6e22e">m</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">md5</span>.<span style="color:#a6e22e">New</span>()
	<span style="color:#a6e22e">m</span>.<span style="color:#a6e22e">Write</span>([]byte(<span style="color:#a6e22e">value</span>))

	<span style="color:#66d9ef">return</span> <span style="color:#a6e22e">hex</span>.<span style="color:#a6e22e">EncodeToString</span>(<span style="color:#a6e22e">m</span>.<span style="color:#a6e22e">Sum</span>(<span style="color:#66d9ef">nil</span>))
}

</code></pre></div><h3 id="第一步-2">第一步</h3>
<p>在先前我们已经把底层方法给封装好了，实质这一步为封装 image 的处理逻辑</p>
<p>在 pkg 目录下新建 upload/image.go 文件，写入文件内容：</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-go" data-lang="go"><span style="color:#f92672">package</span> <span style="color:#a6e22e">upload</span>

<span style="color:#f92672">import</span> (
	<span style="color:#e6db74">&#34;os&#34;</span>
	<span style="color:#e6db74">&#34;path&#34;</span>
	<span style="color:#e6db74">&#34;log&#34;</span>
	<span style="color:#e6db74">&#34;fmt&#34;</span>
	<span style="color:#e6db74">&#34;strings&#34;</span>
	<span style="color:#e6db74">&#34;mime/multipart&#34;</span>

	<span style="color:#e6db74">&#34;github.com/EDDYCJY/go-gin-example/pkg/file&#34;</span>
	<span style="color:#e6db74">&#34;github.com/EDDYCJY/go-gin-example/pkg/setting&#34;</span>
	<span style="color:#e6db74">&#34;github.com/EDDYCJY/go-gin-example/pkg/logging&#34;</span>
	<span style="color:#e6db74">&#34;github.com/EDDYCJY/go-gin-example/pkg/util&#34;</span>
)

<span style="color:#66d9ef">func</span> <span style="color:#a6e22e">GetImageFullUrl</span>(<span style="color:#a6e22e">name</span> <span style="color:#66d9ef">string</span>) <span style="color:#66d9ef">string</span> {
	<span style="color:#66d9ef">return</span> <span style="color:#a6e22e">setting</span>.<span style="color:#a6e22e">AppSetting</span>.<span style="color:#a6e22e">ImagePrefixUrl</span> <span style="color:#f92672">+</span> <span style="color:#e6db74">&#34;/&#34;</span> <span style="color:#f92672">+</span> <span style="color:#a6e22e">GetImagePath</span>() <span style="color:#f92672">+</span> <span style="color:#a6e22e">name</span>
}

<span style="color:#66d9ef">func</span> <span style="color:#a6e22e">GetImageName</span>(<span style="color:#a6e22e">name</span> <span style="color:#66d9ef">string</span>) <span style="color:#66d9ef">string</span> {
	<span style="color:#a6e22e">ext</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">path</span>.<span style="color:#a6e22e">Ext</span>(<span style="color:#a6e22e">name</span>)
	<span style="color:#a6e22e">fileName</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">strings</span>.<span style="color:#a6e22e">TrimSuffix</span>(<span style="color:#a6e22e">name</span>, <span style="color:#a6e22e">ext</span>)
	<span style="color:#a6e22e">fileName</span> = <span style="color:#a6e22e">util</span>.<span style="color:#a6e22e">EncodeMD5</span>(<span style="color:#a6e22e">fileName</span>)

	<span style="color:#66d9ef">return</span> <span style="color:#a6e22e">fileName</span> <span style="color:#f92672">+</span> <span style="color:#a6e22e">ext</span>
}

<span style="color:#66d9ef">func</span> <span style="color:#a6e22e">GetImagePath</span>() <span style="color:#66d9ef">string</span> {
	<span style="color:#66d9ef">return</span> <span style="color:#a6e22e">setting</span>.<span style="color:#a6e22e">AppSetting</span>.<span style="color:#a6e22e">ImageSavePath</span>
}

<span style="color:#66d9ef">func</span> <span style="color:#a6e22e">GetImageFullPath</span>() <span style="color:#66d9ef">string</span> {
	<span style="color:#66d9ef">return</span> <span style="color:#a6e22e">setting</span>.<span style="color:#a6e22e">AppSetting</span>.<span style="color:#a6e22e">RuntimeRootPath</span> <span style="color:#f92672">+</span> <span style="color:#a6e22e">GetImagePath</span>()
}

<span style="color:#66d9ef">func</span> <span style="color:#a6e22e">CheckImageExt</span>(<span style="color:#a6e22e">fileName</span> <span style="color:#66d9ef">string</span>) <span style="color:#66d9ef">bool</span> {
	<span style="color:#a6e22e">ext</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">file</span>.<span style="color:#a6e22e">GetExt</span>(<span style="color:#a6e22e">fileName</span>)
	<span style="color:#66d9ef">for</span> <span style="color:#a6e22e">_</span>, <span style="color:#a6e22e">allowExt</span> <span style="color:#f92672">:=</span> <span style="color:#66d9ef">range</span> <span style="color:#a6e22e">setting</span>.<span style="color:#a6e22e">AppSetting</span>.<span style="color:#a6e22e">ImageAllowExts</span> {
		<span style="color:#66d9ef">if</span> <span style="color:#a6e22e">strings</span>.<span style="color:#a6e22e">ToUpper</span>(<span style="color:#a6e22e">allowExt</span>) <span style="color:#f92672">==</span> <span style="color:#a6e22e">strings</span>.<span style="color:#a6e22e">ToUpper</span>(<span style="color:#a6e22e">ext</span>) {
			<span style="color:#66d9ef">return</span> <span style="color:#66d9ef">true</span>
		}
	}

	<span style="color:#66d9ef">return</span> <span style="color:#66d9ef">false</span>
}

<span style="color:#66d9ef">func</span> <span style="color:#a6e22e">CheckImageSize</span>(<span style="color:#a6e22e">f</span> <span style="color:#a6e22e">multipart</span>.<span style="color:#a6e22e">File</span>) <span style="color:#66d9ef">bool</span> {
	<span style="color:#a6e22e">size</span>, <span style="color:#a6e22e">err</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">file</span>.<span style="color:#a6e22e">GetSize</span>(<span style="color:#a6e22e">f</span>)
	<span style="color:#66d9ef">if</span> <span style="color:#a6e22e">err</span> <span style="color:#f92672">!=</span> <span style="color:#66d9ef">nil</span> {
		<span style="color:#a6e22e">log</span>.<span style="color:#a6e22e">Println</span>(<span style="color:#a6e22e">err</span>)
		<span style="color:#a6e22e">logging</span>.<span style="color:#a6e22e">Warn</span>(<span style="color:#a6e22e">err</span>)
		<span style="color:#66d9ef">return</span> <span style="color:#66d9ef">false</span>
	}

	<span style="color:#66d9ef">return</span> <span style="color:#a6e22e">size</span> <span style="color:#f92672">&lt;=</span> <span style="color:#a6e22e">setting</span>.<span style="color:#a6e22e">AppSetting</span>.<span style="color:#a6e22e">ImageMaxSize</span>
}

<span style="color:#66d9ef">func</span> <span style="color:#a6e22e">CheckImage</span>(<span style="color:#a6e22e">src</span> <span style="color:#66d9ef">string</span>) <span style="color:#66d9ef">error</span> {
	<span style="color:#a6e22e">dir</span>, <span style="color:#a6e22e">err</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">os</span>.<span style="color:#a6e22e">Getwd</span>()
	<span style="color:#66d9ef">if</span> <span style="color:#a6e22e">err</span> <span style="color:#f92672">!=</span> <span style="color:#66d9ef">nil</span> {
		<span style="color:#66d9ef">return</span> <span style="color:#a6e22e">fmt</span>.<span style="color:#a6e22e">Errorf</span>(<span style="color:#e6db74">&#34;os.Getwd err: %v&#34;</span>, <span style="color:#a6e22e">err</span>)
	}

	<span style="color:#a6e22e">err</span> = <span style="color:#a6e22e">file</span>.<span style="color:#a6e22e">IsNotExistMkDir</span>(<span style="color:#a6e22e">dir</span> <span style="color:#f92672">+</span> <span style="color:#e6db74">&#34;/&#34;</span> <span style="color:#f92672">+</span> <span style="color:#a6e22e">src</span>)
	<span style="color:#66d9ef">if</span> <span style="color:#a6e22e">err</span> <span style="color:#f92672">!=</span> <span style="color:#66d9ef">nil</span> {
		<span style="color:#66d9ef">return</span> <span style="color:#a6e22e">fmt</span>.<span style="color:#a6e22e">Errorf</span>(<span style="color:#e6db74">&#34;file.IsNotExistMkDir err: %v&#34;</span>, <span style="color:#a6e22e">err</span>)
	}

	<span style="color:#a6e22e">perm</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">file</span>.<span style="color:#a6e22e">CheckPermission</span>(<span style="color:#a6e22e">src</span>)
	<span style="color:#66d9ef">if</span> <span style="color:#a6e22e">perm</span> <span style="color:#f92672">==</span> <span style="color:#66d9ef">true</span> {
		<span style="color:#66d9ef">return</span> <span style="color:#a6e22e">fmt</span>.<span style="color:#a6e22e">Errorf</span>(<span style="color:#e6db74">&#34;file.CheckPermission Permission denied src: %s&#34;</span>, <span style="color:#a6e22e">src</span>)
	}

	<span style="color:#66d9ef">return</span> <span style="color:#66d9ef">nil</span>
}
</code></pre></div><p>在这里我们实现了 7 个方法，如下：</p>
<ul>
<li>GetImageFullUrl：获取图片完整访问 URL</li>
<li>GetImageName：获取图片名称</li>
<li>GetImagePath：获取图片路径</li>
<li>GetImageFullPath：获取图片完整路径</li>
<li>CheckImageExt：检查图片后缀</li>
<li>CheckImageSize：检查图片大小</li>
<li>CheckImage：检查图片</li>
</ul>
<p>这里基本是对底层代码的二次封装，为了更灵活的处理一些图片特有的逻辑，并且方便修改，不直接对外暴露下层</p>
<h3 id="第二步-2">第二步</h3>
<p>这一步将编写上传图片的业务逻辑，在 routers/api 目录下 新建 upload.go 文件，写入文件内容:</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-go" data-lang="go"><span style="color:#f92672">package</span> <span style="color:#a6e22e">api</span>

<span style="color:#f92672">import</span> (
	<span style="color:#e6db74">&#34;net/http&#34;</span>

	<span style="color:#e6db74">&#34;github.com/gin-gonic/gin&#34;</span>

	<span style="color:#e6db74">&#34;github.com/EDDYCJY/go-gin-example/pkg/e&#34;</span>
	<span style="color:#e6db74">&#34;github.com/EDDYCJY/go-gin-example/pkg/logging&#34;</span>
	<span style="color:#e6db74">&#34;github.com/EDDYCJY/go-gin-example/pkg/upload&#34;</span>
)

<span style="color:#66d9ef">func</span> <span style="color:#a6e22e">UploadImage</span>(<span style="color:#a6e22e">c</span> <span style="color:#f92672">*</span><span style="color:#a6e22e">gin</span>.<span style="color:#a6e22e">Context</span>) {
	<span style="color:#a6e22e">code</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">e</span>.<span style="color:#a6e22e">SUCCESS</span>
	<span style="color:#a6e22e">data</span> <span style="color:#f92672">:=</span> make(<span style="color:#66d9ef">map</span>[<span style="color:#66d9ef">string</span>]<span style="color:#66d9ef">string</span>)

	<span style="color:#a6e22e">file</span>, <span style="color:#a6e22e">image</span>, <span style="color:#a6e22e">err</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">c</span>.<span style="color:#a6e22e">Request</span>.<span style="color:#a6e22e">FormFile</span>(<span style="color:#e6db74">&#34;image&#34;</span>)
	<span style="color:#66d9ef">if</span> <span style="color:#a6e22e">err</span> <span style="color:#f92672">!=</span> <span style="color:#66d9ef">nil</span> {
		<span style="color:#a6e22e">logging</span>.<span style="color:#a6e22e">Warn</span>(<span style="color:#a6e22e">err</span>)
		<span style="color:#a6e22e">code</span> = <span style="color:#a6e22e">e</span>.<span style="color:#a6e22e">ERROR</span>
		<span style="color:#a6e22e">c</span>.<span style="color:#a6e22e">JSON</span>(<span style="color:#a6e22e">http</span>.<span style="color:#a6e22e">StatusOK</span>, <span style="color:#a6e22e">gin</span>.<span style="color:#a6e22e">H</span>{
			<span style="color:#e6db74">&#34;code&#34;</span>: <span style="color:#a6e22e">code</span>,
			<span style="color:#e6db74">&#34;msg&#34;</span>:  <span style="color:#a6e22e">e</span>.<span style="color:#a6e22e">GetMsg</span>(<span style="color:#a6e22e">code</span>),
			<span style="color:#e6db74">&#34;data&#34;</span>: <span style="color:#a6e22e">data</span>,
		})
	}

	<span style="color:#66d9ef">if</span> <span style="color:#a6e22e">image</span> <span style="color:#f92672">==</span> <span style="color:#66d9ef">nil</span> {
		<span style="color:#a6e22e">code</span> = <span style="color:#a6e22e">e</span>.<span style="color:#a6e22e">INVALID_PARAMS</span>
	} <span style="color:#66d9ef">else</span> {
		<span style="color:#a6e22e">imageName</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">upload</span>.<span style="color:#a6e22e">GetImageName</span>(<span style="color:#a6e22e">image</span>.<span style="color:#a6e22e">Filename</span>)
		<span style="color:#a6e22e">fullPath</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">upload</span>.<span style="color:#a6e22e">GetImageFullPath</span>()
		<span style="color:#a6e22e">savePath</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">upload</span>.<span style="color:#a6e22e">GetImagePath</span>()

		<span style="color:#a6e22e">src</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">fullPath</span> <span style="color:#f92672">+</span> <span style="color:#a6e22e">imageName</span>
		<span style="color:#66d9ef">if</span> ! <span style="color:#a6e22e">upload</span>.<span style="color:#a6e22e">CheckImageExt</span>(<span style="color:#a6e22e">imageName</span>) <span style="color:#f92672">||</span> ! <span style="color:#a6e22e">upload</span>.<span style="color:#a6e22e">CheckImageSize</span>(<span style="color:#a6e22e">file</span>) {
			<span style="color:#a6e22e">code</span> = <span style="color:#a6e22e">e</span>.<span style="color:#a6e22e">ERROR_UPLOAD_CHECK_IMAGE_FORMAT</span>
		} <span style="color:#66d9ef">else</span> {
			<span style="color:#a6e22e">err</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">upload</span>.<span style="color:#a6e22e">CheckImage</span>(<span style="color:#a6e22e">fullPath</span>)
			<span style="color:#66d9ef">if</span> <span style="color:#a6e22e">err</span> <span style="color:#f92672">!=</span> <span style="color:#66d9ef">nil</span> {
				<span style="color:#a6e22e">logging</span>.<span style="color:#a6e22e">Warn</span>(<span style="color:#a6e22e">err</span>)
				<span style="color:#a6e22e">code</span> = <span style="color:#a6e22e">e</span>.<span style="color:#a6e22e">ERROR_UPLOAD_CHECK_IMAGE_FAIL</span>
			} <span style="color:#66d9ef">else</span> <span style="color:#66d9ef">if</span> <span style="color:#a6e22e">err</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">c</span>.<span style="color:#a6e22e">SaveUploadedFile</span>(<span style="color:#a6e22e">image</span>, <span style="color:#a6e22e">src</span>); <span style="color:#a6e22e">err</span> <span style="color:#f92672">!=</span> <span style="color:#66d9ef">nil</span> {
				<span style="color:#a6e22e">logging</span>.<span style="color:#a6e22e">Warn</span>(<span style="color:#a6e22e">err</span>)
				<span style="color:#a6e22e">code</span> = <span style="color:#a6e22e">e</span>.<span style="color:#a6e22e">ERROR_UPLOAD_SAVE_IMAGE_FAIL</span>
			} <span style="color:#66d9ef">else</span> {
				<span style="color:#a6e22e">data</span>[<span style="color:#e6db74">&#34;image_url&#34;</span>] = <span style="color:#a6e22e">upload</span>.<span style="color:#a6e22e">GetImageFullUrl</span>(<span style="color:#a6e22e">imageName</span>)
				<span style="color:#a6e22e">data</span>[<span style="color:#e6db74">&#34;image_save_url&#34;</span>] = <span style="color:#a6e22e">savePath</span> <span style="color:#f92672">+</span> <span style="color:#a6e22e">imageName</span>
			}
		}
	}

	<span style="color:#a6e22e">c</span>.<span style="color:#a6e22e">JSON</span>(<span style="color:#a6e22e">http</span>.<span style="color:#a6e22e">StatusOK</span>, <span style="color:#a6e22e">gin</span>.<span style="color:#a6e22e">H</span>{
		<span style="color:#e6db74">&#34;code&#34;</span>: <span style="color:#a6e22e">code</span>,
		<span style="color:#e6db74">&#34;msg&#34;</span>:  <span style="color:#a6e22e">e</span>.<span style="color:#a6e22e">GetMsg</span>(<span style="color:#a6e22e">code</span>),
		<span style="color:#e6db74">&#34;data&#34;</span>: <span style="color:#a6e22e">data</span>,
	})
}
</code></pre></div><p>所涉及的错误码（需在 pkg/e/code.go、msg.go 添加）：</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-go" data-lang="go"><span style="color:#75715e">// 保存图片失败
</span><span style="color:#75715e"></span><span style="color:#a6e22e">ERROR_UPLOAD_SAVE_IMAGE_FAIL</span> = <span style="color:#ae81ff">30001</span>
<span style="color:#75715e">// 检查图片失败
</span><span style="color:#75715e"></span><span style="color:#a6e22e">ERROR_UPLOAD_CHECK_IMAGE_FAIL</span> = <span style="color:#ae81ff">30002</span>
<span style="color:#75715e">// 校验图片错误，图片格式或大小有问题
</span><span style="color:#75715e"></span><span style="color:#a6e22e">ERROR_UPLOAD_CHECK_IMAGE_FORMAT</span> = <span style="color:#ae81ff">30003</span>
</code></pre></div><p>在这一大段的业务逻辑中，我们做了如下事情：</p>
<ul>
<li>c.Request.FormFile：获取上传的图片（返回提供的表单键的第一个文件）</li>
<li>CheckImageExt、CheckImageSize 检查图片大小，检查图片后缀</li>
<li>CheckImage：检查上传图片所需（权限、文件夹）</li>
<li>SaveUploadedFile：保存图片</li>
</ul>
<p>总的来说，就是 入参 -&gt; 检查 -》 保存 的应用流程</p>
<h3 id="第三步">第三步</h3>
<p>打开 routers/router.go 文件，增加路由 <code>r.POST(&quot;/upload&quot;, api.UploadImage)</code> ，如：</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-go" data-lang="go"><span style="color:#66d9ef">func</span> <span style="color:#a6e22e">InitRouter</span>() <span style="color:#f92672">*</span><span style="color:#a6e22e">gin</span>.<span style="color:#a6e22e">Engine</span> {
	<span style="color:#a6e22e">r</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">gin</span>.<span style="color:#a6e22e">New</span>()
    <span style="color:#f92672">...</span>
	<span style="color:#a6e22e">r</span>.<span style="color:#a6e22e">GET</span>(<span style="color:#e6db74">&#34;/auth&#34;</span>, <span style="color:#a6e22e">api</span>.<span style="color:#a6e22e">GetAuth</span>)
	<span style="color:#a6e22e">r</span>.<span style="color:#a6e22e">GET</span>(<span style="color:#e6db74">&#34;/swagger/*any&#34;</span>, <span style="color:#a6e22e">ginSwagger</span>.<span style="color:#a6e22e">WrapHandler</span>(<span style="color:#a6e22e">swaggerFiles</span>.<span style="color:#a6e22e">Handler</span>))
	<span style="color:#a6e22e">r</span>.<span style="color:#a6e22e">POST</span>(<span style="color:#e6db74">&#34;/upload&#34;</span>, <span style="color:#a6e22e">api</span>.<span style="color:#a6e22e">UploadImage</span>)

	<span style="color:#a6e22e">apiv1</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">r</span>.<span style="color:#a6e22e">Group</span>(<span style="color:#e6db74">&#34;/api/v1&#34;</span>)
	<span style="color:#a6e22e">apiv1</span>.<span style="color:#a6e22e">Use</span>(<span style="color:#a6e22e">jwt</span>.<span style="color:#a6e22e">JWT</span>())
	{
		<span style="color:#f92672">...</span>
	}

	<span style="color:#66d9ef">return</span> <span style="color:#a6e22e">r</span>
}
</code></pre></div><h3 id="验证-1">验证</h3>
<p>最后我们请求一下上传图片的接口，测试所编写的功能</p>
<p><img src="https://s2.ax1x.com/2020/02/15/1xumb8.jpg" alt="image"></p>
<p>检查目录下是否含文件（注意权限问题）</p>
<pre><code>$ pwd
$GOPATH/src/github.com/EDDYCJY/go-gin-example/runtime/upload/images

$ ll
... 96a3be3cf272e017046d1b2674a52bd3.jpg
... c39fa784216313cf2faa7c98739fc367.jpeg
</code></pre><p>在这里我们一共返回了 2 个参数，一个是完整的访问 URL，另一个为保存路径</p>
<h2 id="实现-httpfileserver">实现 http.FileServer</h2>
<p>在完成了上一小节后，我们还需要让前端能够访问到图片，一般是如下：</p>
<ul>
<li>CDN</li>
<li>http.FileSystem</li>
</ul>
<p>在公司的话，CDN 或自建分布式文件系统居多，也不需要过多关注。而在实践里的话肯定是本地搭建了，Go 本身对此就有很好的支持，而 Gin 更是再封装了一层，只需要在路由增加一行代码即可</p>
<h3 id="rstaticfs">r.StaticFS</h3>
<p>打开 routers/router.go 文件，增加路由 <code>r.StaticFS(&quot;/upload/images&quot;, http.Dir(upload.GetImageFullPath()))</code>，如：</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-go" data-lang="go"><span style="color:#66d9ef">func</span> <span style="color:#a6e22e">InitRouter</span>() <span style="color:#f92672">*</span><span style="color:#a6e22e">gin</span>.<span style="color:#a6e22e">Engine</span> {
    <span style="color:#f92672">...</span>
	<span style="color:#a6e22e">r</span>.<span style="color:#a6e22e">StaticFS</span>(<span style="color:#e6db74">&#34;/upload/images&#34;</span>, <span style="color:#a6e22e">http</span>.<span style="color:#a6e22e">Dir</span>(<span style="color:#a6e22e">upload</span>.<span style="color:#a6e22e">GetImageFullPath</span>()))

	<span style="color:#a6e22e">r</span>.<span style="color:#a6e22e">GET</span>(<span style="color:#e6db74">&#34;/auth&#34;</span>, <span style="color:#a6e22e">api</span>.<span style="color:#a6e22e">GetAuth</span>)
	<span style="color:#a6e22e">r</span>.<span style="color:#a6e22e">GET</span>(<span style="color:#e6db74">&#34;/swagger/*any&#34;</span>, <span style="color:#a6e22e">ginSwagger</span>.<span style="color:#a6e22e">WrapHandler</span>(<span style="color:#a6e22e">swaggerFiles</span>.<span style="color:#a6e22e">Handler</span>))
	<span style="color:#a6e22e">r</span>.<span style="color:#a6e22e">POST</span>(<span style="color:#e6db74">&#34;/upload&#34;</span>, <span style="color:#a6e22e">api</span>.<span style="color:#a6e22e">UploadImage</span>)
    <span style="color:#f92672">...</span>
}
</code></pre></div><h3 id="它做了什么">它做了什么</h3>
<p>当访问 $HOST/upload/images 时，将会读取到 $GOPATH/src/github.com/EDDYCJY/go-gin-example/runtime/upload/images 下的文件</p>
<p>而这行代码又做了什么事呢，我们来看看方法原型</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-go" data-lang="go"><span style="color:#75715e">// StaticFS works just like `Static()` but a custom `http.FileSystem` can be used instead.
</span><span style="color:#75715e">// Gin by default user: gin.Dir()
</span><span style="color:#75715e"></span><span style="color:#66d9ef">func</span> (<span style="color:#a6e22e">group</span> <span style="color:#f92672">*</span><span style="color:#a6e22e">RouterGroup</span>) <span style="color:#a6e22e">StaticFS</span>(<span style="color:#a6e22e">relativePath</span> <span style="color:#66d9ef">string</span>, <span style="color:#a6e22e">fs</span> <span style="color:#a6e22e">http</span>.<span style="color:#a6e22e">FileSystem</span>) <span style="color:#a6e22e">IRoutes</span> {
	<span style="color:#66d9ef">if</span> <span style="color:#a6e22e">strings</span>.<span style="color:#a6e22e">Contains</span>(<span style="color:#a6e22e">relativePath</span>, <span style="color:#e6db74">&#34;:&#34;</span>) <span style="color:#f92672">||</span> <span style="color:#a6e22e">strings</span>.<span style="color:#a6e22e">Contains</span>(<span style="color:#a6e22e">relativePath</span>, <span style="color:#e6db74">&#34;*&#34;</span>) {
		panic(<span style="color:#e6db74">&#34;URL parameters can not be used when serving a static folder&#34;</span>)
	}
	<span style="color:#a6e22e">handler</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">group</span>.<span style="color:#a6e22e">createStaticHandler</span>(<span style="color:#a6e22e">relativePath</span>, <span style="color:#a6e22e">fs</span>)
	<span style="color:#a6e22e">urlPattern</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">path</span>.<span style="color:#a6e22e">Join</span>(<span style="color:#a6e22e">relativePath</span>, <span style="color:#e6db74">&#34;/*filepath&#34;</span>)

	<span style="color:#75715e">// Register GET and HEAD handlers
</span><span style="color:#75715e"></span>	<span style="color:#a6e22e">group</span>.<span style="color:#a6e22e">GET</span>(<span style="color:#a6e22e">urlPattern</span>, <span style="color:#a6e22e">handler</span>)
	<span style="color:#a6e22e">group</span>.<span style="color:#a6e22e">HEAD</span>(<span style="color:#a6e22e">urlPattern</span>, <span style="color:#a6e22e">handler</span>)
	<span style="color:#66d9ef">return</span> <span style="color:#a6e22e">group</span>.<span style="color:#a6e22e">returnObj</span>()
}
</code></pre></div><p>首先在暴露的 URL 中禁止了 * 和 : 符号的使用，通过 <code>createStaticHandler</code> 创建了静态文件服务，实质最终调用的还是 <code>fileServer.ServeHTTP</code> 和一些处理逻辑了</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-go" data-lang="go"><span style="color:#66d9ef">func</span> (<span style="color:#a6e22e">group</span> <span style="color:#f92672">*</span><span style="color:#a6e22e">RouterGroup</span>) <span style="color:#a6e22e">createStaticHandler</span>(<span style="color:#a6e22e">relativePath</span> <span style="color:#66d9ef">string</span>, <span style="color:#a6e22e">fs</span> <span style="color:#a6e22e">http</span>.<span style="color:#a6e22e">FileSystem</span>) <span style="color:#a6e22e">HandlerFunc</span> {
	<span style="color:#a6e22e">absolutePath</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">group</span>.<span style="color:#a6e22e">calculateAbsolutePath</span>(<span style="color:#a6e22e">relativePath</span>)
	<span style="color:#a6e22e">fileServer</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">http</span>.<span style="color:#a6e22e">StripPrefix</span>(<span style="color:#a6e22e">absolutePath</span>, <span style="color:#a6e22e">http</span>.<span style="color:#a6e22e">FileServer</span>(<span style="color:#a6e22e">fs</span>))
	<span style="color:#a6e22e">_</span>, <span style="color:#a6e22e">nolisting</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">fs</span>.(<span style="color:#f92672">*</span><span style="color:#a6e22e">onlyfilesFS</span>)
	<span style="color:#66d9ef">return</span> <span style="color:#66d9ef">func</span>(<span style="color:#a6e22e">c</span> <span style="color:#f92672">*</span><span style="color:#a6e22e">Context</span>) {
		<span style="color:#66d9ef">if</span> <span style="color:#a6e22e">nolisting</span> {
			<span style="color:#a6e22e">c</span>.<span style="color:#a6e22e">Writer</span>.<span style="color:#a6e22e">WriteHeader</span>(<span style="color:#ae81ff">404</span>)
		}
		<span style="color:#a6e22e">fileServer</span>.<span style="color:#a6e22e">ServeHTTP</span>(<span style="color:#a6e22e">c</span>.<span style="color:#a6e22e">Writer</span>, <span style="color:#a6e22e">c</span>.<span style="color:#a6e22e">Request</span>)
	}
}
</code></pre></div><h4 id="httpstripprefix">http.StripPrefix</h4>
<p>我们可以留意下 <code>fileServer := http.StripPrefix(absolutePath, http.FileServer(fs))</code> 这段语句，在静态文件服务中很常见，它有什么作用呢？</p>
<p><code>http.StripPrefix</code> 主要作用是从请求 URL 的路径中删除给定的前缀，最终返回一个 <code>Handler</code></p>
<p>通常 http.FileServer 要与 http.StripPrefix 相结合使用，否则当你运行：</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-go" data-lang="go"><span style="color:#a6e22e">http</span>.<span style="color:#a6e22e">Handle</span>(<span style="color:#e6db74">&#34;/upload/images&#34;</span>, <span style="color:#a6e22e">http</span>.<span style="color:#a6e22e">FileServer</span>(<span style="color:#a6e22e">http</span>.<span style="color:#a6e22e">Dir</span>(<span style="color:#e6db74">&#34;upload/images&#34;</span>)))
</code></pre></div><p>会无法正确的访问到文件目录，因为 <code>/upload/images</code> 也包含在了 URL 路径中，必须使用：</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-go" data-lang="go"><span style="color:#a6e22e">http</span>.<span style="color:#a6e22e">Handle</span>(<span style="color:#e6db74">&#34;/upload/images&#34;</span>, <span style="color:#a6e22e">http</span>.<span style="color:#a6e22e">StripPrefix</span>(<span style="color:#e6db74">&#34;upload/images&#34;</span>, <span style="color:#a6e22e">http</span>.<span style="color:#a6e22e">FileServer</span>(<span style="color:#a6e22e">http</span>.<span style="color:#a6e22e">Dir</span>(<span style="color:#e6db74">&#34;upload/images&#34;</span>))))
</code></pre></div><h4 id="filepath">/*filepath</h4>
<p>到下面可以看到 <code>urlPattern := path.Join(relativePath, &quot;/*filepath&quot;)</code>，<code>/*filepath</code> 你是谁，你在这里有什么用，你是 Gin 的产物吗?</p>
<p>通过语义可得知是路由的处理逻辑，而 Gin 的路由是基于 httprouter 的，通过查阅文档可得到以下信息</p>
<pre><code>Pattern: /src/*filepath

 /src/                     match
 /src/somefile.go          match
 /src/subdir/somefile.go   match
</code></pre><p><code>*filepath</code> 将匹配所有文件路径，并且 <code>*filepath</code> 必须在 Pattern 的最后</p>
<h3 id="验证-2">验证</h3>
<p>重新执行 <code>go run main.go</code> ，去访问刚刚在 upload 接口得到的图片地址，检查 http.FileSystem 是否正常</p>
<p><img src="https://s2.ax1x.com/2020/02/15/1xu4Gd.jpg" alt="image"></p>
<h2 id="修改文章接口">修改文章接口</h2>
<p>接下来，需要你修改 routers/api/v1/article.go 的 AddArticle、EditArticle 两个接口</p>
<ul>
<li>新增、更新文章接口：支持入参 cover_image_url</li>
<li>新增、更新文章接口：增加对 cover_image_url 的非空、最长长度校验</li>
</ul>
<p>这块前面文章讲过，如果有问题可以参考项目的代码 👌</p>
<h2 id="总结">总结</h2>
<p>在这章节中，我们简单的分析了下需求，对应用做出了一个小规划并实施</p>
<p>完成了清单中的功能点和优化，在实际项目中也是常见的场景，希望你能够细细品尝并针对一些点进行深入学习</p>
<h2 id="参考">参考</h2>
<h3 id="本系列示例代码">本系列示例代码</h3>
<ul>
<li><a href="https://github.com/EDDYCJY/go-gin-example">go-gin-example</a></li>
</ul>
<h2 id="关于">关于</h2>
<h3 id="修改记录">修改记录</h3>
<ul>
<li>第一版：2018 年 02 月 16 日发布文章</li>
<li>第二版：2019 年 10 月 02 日修改文章</li>
</ul>
<h2 id="heading">？</h2>
<p>如果有任何疑问或错误，欢迎在 <a href="https://github.com/EDDYCJY/blog">issues</a> 进行提问或给予修正意见，如果喜欢或对你有所帮助，欢迎 Star，对作者是一种鼓励和推进。</p>
<h3 id="我的公众号">我的公众号</h3>
<p><img src="https://image.eddycjy.com/8d0b0c3a11e74efd5fdfd7910257e70b.jpg" alt="image"></p>


                                        
                                        
                                        
                                        <div class="rp4wp-related-posts">
                                            <h3>相关文章</h3>
                                            <ul>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.site/posts/go/gin/2018-04-29-cron/">「连载十一」Cron定时任务</a>
                                                    </div>
                                                </li>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.site/posts/go/gin/2018-04-15-gorm-callback/">「连载十」定制 GORM Callbacks</a>
                                                    </div>
                                                </li>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.site/posts/go/gin/2018-03-26-cgo/">「番外」Golang 交叉编译</a>
                                                    </div>
                                                </li>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.site/posts/go/gin/2018-03-24-golang-docker/">「连载九」将Golang应用部署到Docker</a>
                                                    </div>
                                                </li>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.site/posts/go/gin/2018-03-18-swagger/">「连载八」为它加上Swagger</a>
                                                    </div>
                                                </li>
                                                
                                            </ul>
                                        </div>
                                        
                                        
                                    </div>

                                    
                                    
                                    

                                    
                                    <div class="post-meta">
                                        
                                        
                                        <div class="post-tags">
                                            <ul>
                                            
                                            <li>
                                                <a href="/tags/go" title="View all posts tagged match">go</a>
                                            </li>
                                            
                                            <li>
                                                <a href="/tags/gin" title="View all posts tagged match">gin</a>
                                            </li>
                                            
                                            </ul>
                                        </div>
                                        
                                        
                                        <nav class="further-reading">
                                            
                                            <div class="previous">
                                                <span>&lt;&lt; Prev</span>
                                                <a href="https://www.lican.site/posts/go/talk/2018-05-21-go-fake-useragent/"
                                                    rel="prev">Go 的 fake-useragent 了解一下</a> </div>
                                            
                                            
                                            <div class="next">
                                                <span>Next >></span>
                                                <a href="https://www.lican.site/posts/go/gin/2018-06-02-application-redis/">「连载十三」优化你的应用结构和实现Redis缓存</a> 
                                            </div>
                                            
                                        </nav>
                                    </div>
                                    
                                    

                                    
                                    
                                    

                                </div>
                            </article>
                        </div>
                    </div>
                </section>
                <aside class="sidebar sidebar-primary" id="sidebar-primary" role="complementary">
    <h1 class="screen-reader-text">Sidebar</h1>
    

    
    
    <section id="text-2" class="widget widget_text">
        <div class="textwidget">
            
            <div id="profile">
                <div id="profile_picture"><img src="https://www.lican.site/logo/logo.png"></div>
                <div id="profile_intro">
                    <p><span class="name">Lican</span></p>
                    <p class="intro">全栈开发者，爱好造轮子。</p>
                </div>
            </div>
            
            <p>
                <script type="text/javascript">
                    (function ($) {
                        $(document).ready(function () {
                            var menuPrimaryContainer = $('#menu-primary-container');
                            var profile = $('#text-2');
                            $('#toggle-navigation').click(function () {
                                if (menuPrimaryContainer.hasClass('open')) {
                                    profile.removeClass('open');
                                } else {
                                    profile.addClass('open');
                                }
                            });
                        });
                    })(jQuery);
                </script>
            </p>
        </div>
    </section>
    
    
    
    
    
    <section id="text-5" class="widget widget_text">
        <h2 class="widget-title">开源项目</h2>
        <div class="textwidget">
            <div id="projects" style="line-height: 22px;">
                
                <a href="https://github.com/idoubi/gonews"
                    target="_blank">gonews</a>: &nbsp;Daily news for golang<br>
                
                <a href="https://github.com/idoubi/sql2struct"
                    target="_blank">sql2struct</a>: &nbsp;Generate go struct according to SQL<br>
                
                <a href="https://github.com/idoubi/goz"
                    target="_blank">goz</a>: &nbsp;Request library used in golang<br>
                
        </div>
    </section>
    
    

    
    
    
    
    

    
    
    

    
    
    

    
    
    
    
</aside>
            </div>
        </div>

        <footer id="site-footer" class="site-footer" role="contentinfo">
    <div class="max-width">
    </div>
    <div class="footer">
        <div id="footercontent">
            © lican.vip All rights reserved<br/>
            Built with Hugo Theme <a href="https://github.com/idoubi/hugo-theme-period" target="_blank">Period</a>
        </div>
    </div>
</footer>

<script>
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?e8351b6d4626d5881d439ea1f6184baa";
      var s = document.getElementsByTagName("script")[0]; 
      s.parentNode.insertBefore(hm, s);
    })();
</script>
    
    
    </div>
    
</body>

</html>